package com.yc.navy.goods.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.http.HttpSession;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.yc.navy.goods.bean.MemberInfo;
import com.yc.navy.goods.dto.ConstantInfoDTO;
import com.yc.navy.goods.dto.MemberInfoDTO;
import com.yc.navy.goods.dto.PasswordDTO;
import com.yc.navy.goods.enums.ResultEnum;
import com.yc.navy.goods.service.IMemberInfoService;
import com.yc.navy.goods.util.ConstantInfo;
import com.yc.navy.goods.util.SendEmailCode;
import com.yc.navy.goods.util.StringUtil;
import com.yc.navy.goods.vo.ResultVO;
import com.yc.navy.goods.vo.StreamVO;

@RestController
@RequestMapping("/member")
public class MemberInfoController {
	@Autowired
	private SendEmailCode sendEmail;
	
	@Autowired
	private IMemberInfoService memberInfoService; 
	
	private static final String APP_ID = "36811576";
		
	private static final String API_KEY = "K2ZgEvDApi8jrHtqIxcjOVOD";
		
	private static final String SECRET_KEY = "xb5uYUYdKvZPWC23Dcmx7eUGpzhamN1c";
	
	private String totalcode = " ";
	
	private MemberInfo repwdmf;
	
	@RequestMapping("/sendCode")
	public ResultVO sendEmail(String email,String nickName,HttpSession session) {
		String code = " ";
		Random r = new Random();
		while(code.length()<6) {
			code += r.nextInt(10);
		}
		if(sendEmail.sendEmail(email, code, nickName)) {
			session.setAttribute(ConstantInfoDTO.EMAILCHECK,code);
			
			TimerTask task = new TimerTask() {
				@Override
				public void run() {
					session.removeAttribute(ConstantInfoDTO.EMAILCHECK);
				}};
				Timer timer = new Timer();
				timer.schedule(task,100000);
				return new ResultVO(ResultEnum.SUCCESS);
		}
		return new ResultVO(ResultEnum.ERROR);
	}
	
	@RequestMapping("/reg")
	public ResultVO reg(HttpSession session,MemberInfo mf,String emailcode) {
		String code = (String) session.getAttribute(ConstantInfoDTO.EMAILCHECK);
		
		if(!emailcode.trim().equals(code.trim())) {
			return new ResultVO(ResultEnum.CODE_ERROR);
		}
		int result = memberInfoService.reg(mf);
		if(result <=0) {
			return new ResultVO(ResultEnum.ERROR);
		}
		return new ResultVO(ResultEnum.SUCCESS);
	}
	
	@RequestMapping("/login")
	public ResultVO login(HttpSession session,MemberInfo mf) {
		MemberInfo memberInfo = memberInfoService.login(mf);
		if(memberInfo == null) {
			return new ResultVO(ResultEnum.ERROR);
		}
		
		MemberInfoDTO memberDTO = new MemberInfoDTO();
		BeanUtils.copyProperties(memberInfo, memberDTO);
		session.setAttribute(ConstantInfoDTO.LOGINCHECK, memberDTO);
		
		memberInfoService.addNumber(memberInfo.getMid());
		return new ResultVO(ResultEnum.SUCCESS,memberInfo);
	}
	
	@RequestMapping("/repwdCode")
	public ResultVO getRepwdEmail(HttpSession session,MemberInfo mf) {
		String email = memberInfoService.getRepwdEmail(mf);
		if(email == null || "".equals(email)) {
			return new ResultVO(ResultEnum.NOTFOUND);
		}
		
		//session.setAttribute(ConstantInfoDTO.REPWDUSER, mf);
		repwdmf = mf;
		
		String code = " ";
		Random r = new Random();
		while(code.length()<6) {
			code += r.nextInt(10);
		}
		
		String nickName = null;
		if(!StringUtil.checkNull(mf.getNickName())) {
			nickName = mf.getNickName();
		}else if(!StringUtil.checkNull(mf.getTel())) {
			nickName = mf.getTel();
		}
		totalcode = code;
		//session.setAttribute(ConstantInfoDTO.REPWDEMAILCHECK,code);
		if(sendEmail.sendEmail(email, code, nickName)) {
			TimerTask task = new TimerTask() {
				@Override
				public void run() {
					//session.removeAttribute(ConstantInfoDTO.REPWDEMAILCHECK);
					totalcode = " ";
				}};
				Timer timer = new Timer();
				timer.schedule(task,100000);
				return new ResultVO(ResultEnum.SUCCESS,code);
		}
		return new ResultVO(ResultEnum.ERROR);
	}
	
	@RequestMapping("/repwd")
	public ResultVO repwd(HttpSession session,String pwd) {
		//String code = (String) session.getAttribute(ConstantInfoDTO.REPWDEMAILCHECK);
		String code = totalcode;
		if(StringUtil.checkNull(code)) {
			return new ResultVO(ResultEnum.CODE_ERROR);
		}
		
		//MemberInfoDTO mf = (MemberInfoDTO) repwdmf;//session.getAttribute(ConstantInfoDTO.REPWDUSER);
		//MemberInfo member = new MemberInfo();
		repwdmf.setPwd(pwd);
		//BeanUtils.copyProperties(mf, member);
		
		int result = memberInfoService.repassword(repwdmf);
		repwdmf = null;
		if(result <= 0) {
			return new ResultVO(ResultEnum.ERROR);
		}
		return new ResultVO(ResultEnum.SUCCESS);
	}
	
	/**
	 * 查询所有用户
	 * @param session
	 * @param page
	 * @param limit
	 * @return
	 */
	@GetMapping("/finds")
	@ResponseBody
	public StreamVO members(HttpSession session, @RequestParam("page") int page,@RequestParam("limit") int limit) {
		Object obj = session.getAttribute(ConstantInfoDTO.CURRENTLOGINADMIN);
		if(obj == null) {
			return new StreamVO(ResultEnum.NOTLOGIN);
		}
		
		Map<String,Object> map = new HashMap<String,Object>();
		if(!StringUtil.checkNull(page,limit)){
			map.put("page", page);
			map.put("limit",limit);
		}
		
		return memberInfoService.findByPageForBack(map);
	}
	
	@RequestMapping("/checklogin")
	public ResultVO checklogin(HttpSession session) {
		Object obj =   session.getAttribute(ConstantInfoDTO.LOGINCHECK);
		if(obj == null) {
			return new ResultVO(ResultEnum.NOTLOGIN);
		}
		return new ResultVO(ResultEnum.SUCCESS,obj);
	}
	
	@Transactional
	@RequestMapping("/updateMember")
	public ResultVO updateMember(HttpSession session,MemberInfo member) {
		MemberInfoDTO obj = (MemberInfoDTO) session.getAttribute(ConstantInfoDTO.LOGINCHECK);
		if(obj == null ) {
			return new ResultVO(ResultEnum.NOTLOGIN);
		}
		int mid = obj.getMid();
		member.setMid(mid);
		MemberInfoDTO memberDTO = new MemberInfoDTO();
		BeanUtils.copyProperties(member, memberDTO);
		
		if(memberDTO == obj) {
			return new ResultVO(ResultEnum.SUCCESS);
		}
		int result = memberInfoService.updateMember(member);
		if(result <= 0) {
			return new ResultVO(ResultEnum.ERROR);
		}
		return new ResultVO(ResultEnum.SUCCESS);
	}
	
	@RequestMapping("/updatepassword")
	public ResultVO updatepassword(HttpSession session,PasswordDTO pwd) {
		MemberInfoDTO obj = (MemberInfoDTO) session.getAttribute(ConstantInfoDTO.LOGINCHECK);
		if(obj == null ) {
			return new ResultVO(ResultEnum.NOTLOGIN);
		}
		int mid = obj.getMid();
		pwd.setMid(mid);
		int result = memberInfoService.updatepassword(pwd);
		if(result <= 0) {
			return new ResultVO(ResultEnum.ERROR);
		}
		return new ResultVO(ResultEnum.SUCCESS);
	}
	
	@PostMapping("/rechecklogin")
	public ResultVO rechecklogin(HttpSession session) {
		MemberInfoDTO obj = (MemberInfoDTO) session.getAttribute(ConstantInfoDTO.LOGINCHECK);
		if(obj == null ) {
			return new ResultVO(ResultEnum.NOTLOGIN);
		}
		Integer mid = obj.getMid();
		MemberInfo member = memberInfoService.rechecklogin(mid);
		if(member == null ) {
			return new ResultVO(ResultEnum.ERROR);
		}
		return new ResultVO(ResultEnum.SUCCESS,member);
	}
	
	/**
	 * 更改头像
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	@PostMapping("/updataPhoto")
	public ResultVO updataPhoto(HttpSession session, @RequestParam("photo") String photo) throws IOException {
		System.out.println(photo);
		MemberInfoDTO mf = (MemberInfoDTO) session.getAttribute(ConstantInfoDTO.LOGINCHECK);
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("photo", photo);
		map.put("mid", mf.getMid());
		
		int result = memberInfoService.updataPhoto(map);
		
		System.out.println(result);
		if (result == -1) {
			return new ResultVO(ResultEnum.ERROR);
		}
		
		if (result > 0) {
			return new ResultVO(ResultEnum.SUCCESS);
		}
		
		return new ResultVO(ResultEnum.ERROR);
	}
	
	/**
	 * 上传图片
	 * @param upload
	 * @return
	 */
	@PostMapping("/upload")
	public Map<String ,Object> upload(@RequestParam("file") MultipartFile upload){
		
		String savepath = "";
		File dest = null;
		Map<String, Object> map = new HashMap<String, Object>();
		if (upload != null && upload.getSize() > 0) {
			try {
				
				savepath = ConstantInfo.UPLOADPATH + "/" + System.currentTimeMillis() + "_" + upload.getOriginalFilename();
				System.out.println("常量" + ConstantInfo.UPLOADPATH);
				System.out.println("常量" + ConstantInfo.basepath);
				System.out.println("常量" + savepath);
				System.out.println("常量" + dest);
				dest = new File(ConstantInfo.basepath, savepath);
				upload.transferTo(dest);
				
				// TODO 添加图片水印
				map.put("filename", upload.getOriginalFilename());
				map.put("uploaded", 1);
				map.put("url", "../../../" + savepath);
			} catch (IllegalStateException | IOException e) {
				e.printStackTrace();
			}
		}
		return map;
	}
}
